<?php
Yii::import('Core.extensions.i18n.LocaleManager');
class LanguageController extends BackOfficeController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => FSM::run('Admin.Language.get', array('id' => $id))->model,
        ));
    }

    /**
     * Ajax toggle change status.
     *
     */
    public function actionStatus()
    {
        $result = FSM::run('Admin.Language.changeStatus', $_GET);
        if ($result->hasErrors()) {
            echo $result->getError('ErrorCode');
        } elseif (!Yii::app()->request->isAjaxRequest) {
            // only redirect user to the admin page if it is not an AJAX request
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->actionUpdate();
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {
        $siteId = $this->get('siteId', 0);
        $languageList = LocaleManager::getStandardLocales();
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax', '') == 'language-form');
            $result = FSM::run('Admin.Language.save', $_POST);
            $model = $result->model;
            //Get Original Supported Languages
            if ($this->post('ajax', '') == 'language-form') {
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            if (!$result->hasErrors()) {
                //Then add a live workflow
                $saveWorkflow = FSM::run('Admin.Language.addWorkflow', array('model' => $model));
                $this->message = Yii::t('Core', 'Language has been added successfully. (' . $saveWorkflow->count . ' workflow added) ');
                $this->redirect($this->createUrl('admin', array('siteId' => $siteId)));
                //$this->refresh();
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new Language();
                if ($siteId != 0)
                    $model->site_id = $siteId;
            } else {
                $model = FSM::run('Admin.Language.get', array('id' => $id))->model;
            }
            //Exclude all language that has added to active site.
            $activeSite = ($siteId != 0) ? $siteId : Yii::app()->cmsManager->site['id'];
            $languagesAdded = Language::model()->findAll('site_id=:site_id', array(':site_id' => $activeSite));
            if (is_array($languagesAdded)) {
                foreach ($languagesAdded as $language) {
                    //Exclude all languages that had been added to language table.
                    unset($languageList[$language->locale_id]);
                }
            }
        }

        $this->render('update', array('model' => $model, 'languageList' => $languageList));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            if (($id = $this->get('id', null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',', $id);

                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Admin.Language.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif (!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400, Yii::t('Core', 'Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400, Yii::t('Core', 'Invalid request. Please do not repeat this request again.'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $siteId = $this->get('siteId', 0);
        if ($siteId == 0)
            $this->redirect('/Admin/default/index');
        $model = new Language('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Language']))
            $model->attributes = $_GET['Language'];
        $model->site_id = $siteId;
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionSupported()
    {
        $this->render('supported');
    }

    /**
     * Refresh available language list
     * @throws CHttpException
     */
    public function actionRefreshLanguageList()
    {
        $siteId = $this->get('siteId', 0);
        if ($siteId == 0 || !Yii::app()->request->isAjaxRequest) {
            throw new CHttpException(500, 'Request invalid');
        }
        $languageList = LocaleManager::getStandardLocales();
        $activeSite = ($siteId != 0) ? $siteId : Yii::app()->cmsManager->site['id'];
        $languagesAdded = Language::model()->findAll('site_id=:site_id', array(':site_id' => $activeSite));
        if (is_array($languagesAdded)) {
            foreach ($languagesAdded as $language) {
                //Exclude all languages that had been added to language table.
                unset($languageList[$language->locale_id]);
            }
        }
        $html = "<option value=\"\">Select one</option>\n";
        foreach ($languageList as $localeId => $name) {
            $html .= "<option value=\"{$localeId}\">{$name}</option>\n";
        }
        echo $html;

    }
}
